package assignment;

import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: xiaotutu
 * Date: 2025-02-19
 * Time: 22:21
 */
//给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
//实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
//其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
//最终再汇总两个和, 进行相加
//记录程序的执行时间.

public class Demo7 {
    public static int sum1 = 0;
    public static int sum2 = 0;

    public static void main(String[] args) throws InterruptedException {
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        int[] array = new int[1000_0000];
        Random random = new Random(100);

        // 初始化数组，填充随机数 1-100
        for (int i = 0; i < 1000_0000; i++) {
            array[i] = 1 + random.nextInt(100);
        }
        // 线程1 计算偶下标的值
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < array.length; i += 2) {
                sum1 += array[i];
            }

        });
        // 线程2 计算奇下标的值
        Thread thread2 = new Thread(() -> {
            for (int i = 1; i < array.length; i += 2) {
                sum2 += array[i];
            }
        });


        thread1.start();
        thread2.start();

        // thread1.join();
        // thread2.join();

        long endTime = System.currentTimeMillis();

        long time = endTime - startTime;
        int sum = sum1 + sum2;
        System.out.println("totalSum = " + sum);
        System.out.println("time : " + time + "ms ");
    }
}
